package org.tribalwarstoolbox.helpers.images;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
/**
 * 
 * Class that helps to include Images in userscripts
 * @version 1.0
 * @category helpers
 * @author Mathias
 *
 */

public class ImgClassMaker {
	
	
	public static final String CLASSNAME= "ImageHolder";
	public static final String CLASSPATH = "src/org/tribalwarstoolbox/client/images/";
	public static final String CLASSPACKAGE = "org.tribalwarstoolbox.client.images";
	

	public static void main(String[] args) {
		
		File file = new File("img/");
		System.out.println("Reading directory : " + file.getAbsolutePath());
		File[] files = file.listFiles();
		if (files == null){
			System.out.println("Error reading directory : " + file.getAbsolutePath());
			return;
		}
		StringBuffer sb = new StringBuffer();
		sb.append("package ");
		sb.append(ImgClassMaker.CLASSPACKAGE);
		sb.append(";\n\n\tpublic class ");
		sb.append(ImgClassMaker.CLASSNAME);
		sb.append(" {\n\n");
			
		for (int i = 0; i < files.length; i++) {

			sb.append("\t\tpublic static String get");
			sb.append(files[i].getName().substring(0,
					files[i].getName().indexOf('.')));
			sb.append("Gfx() {\n\t\t\treturn \"data:image/png;base64,");
			sb.append(Base64Coder.encodeString(readFileContent(files[i])));
			sb.append("\";\n\t\t}\n");

		}
		sb.append("\n}\n");
		System.out.println("Start writing the class file");
		createClass(sb.toString());
		System.out.println("Sucess");

	}

	
	/**
	 * simple File-Writer
	 * 
	 * @param content of the class
	 */
	public static void createClass(String content){
		try {
			File output = new File(ImgClassMaker.CLASSPATH+ImgClassMaker.CLASSNAME+".java");
			if (!output.exists()) {
				output.createNewFile();
			}
			BufferedWriter bw = new BufferedWriter(new FileWriter(output));
			bw.write(content);
			bw.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * simple File-Reader<br/>
	 * returns the content of a file
	 * 
	 * @param file to read
	 * @return
	 */
	public static String readFileContent(File toRead) {
		System.out.println("Reading file: " + toRead.getName());
		StringBuffer filecontent = new StringBuffer();

		try {
			BufferedReader br = new BufferedReader(new FileReader(toRead));
			String line;
			while ((line = br.readLine()) != null) {
				filecontent.append(line);
			}
			br.close();
		} catch (Exception e) {
			System.out.println("Error Reading file: " + toRead.getName());
		}
		return filecontent.toString();
	}
}
